package com.blockmeta.bbs.businesslibrary.launch;

import android.Manifest;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.NotificationManagerCompat;
import androidx.viewpager.widget.ViewPager;
import android.text.TextUtils;
import com.blankj.utilcode.util.LogUtils;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.callback.NavCallback;
import com.alibaba.android.arouter.launcher.ARouter;
import com.blankj.utilcode.util.ToastUtils;
import com.blockmeta.bbs.baselibrary.base.adapter.QuickPagerAdapter;
import com.blockmeta.bbs.baselibrary.base.app.BaseApp;
import com.blockmeta.bbs.baselibrary.net.callback.SuccessCallBack;
import com.blockmeta.bbs.baselibrary.provider.IApplicationProvider;
import com.blockmeta.bbs.baselibrary.utils.NetworkStateUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.permission.Permissions;
import com.blockmeta.bbs.businesslibrary.BaseBussinessApp;
import com.blockmeta.bbs.businesslibrary.BuildConfig;
import com.blockmeta.bbs.businesslibrary.R;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.dialog.CheckDialog;
import com.blockmeta.bbs.businesslibrary.popwindow.UserAgreementPopupWindow;
import com.blockmeta.bbs.businesslibrary.service.MyGTIntentService;
import com.blockmeta.bbs.businesslibrary.service.MyGTPushService;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.DeviceUtil;
import com.blockmeta.bbs.businesslibrary.widget.CircleIndicator;
import com.hellobike.flutter.thrio.navigator.ThrioNavigator;
import com.igexin.sdk.PushManager;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by author on 2017/12/29.
 */

public class SplashActivity extends BaseActivity implements View.OnClickListener {
    private View view;
    protected ResourceDownload m_rscDL;
    private ConstraintLayout mGuideContainer;
    private ViewPager mViewPager;
    private CircleIndicator mIndicator;
    private static final int REQUEST_PERMISSION = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //获取推送权限
        boolean areNotificationsEnabled = NotificationManagerCompat.from(mContext).areNotificationsEnabled();
        SharedPreferenceUtil.getBoolean(mContext, Constant.NOTIFATION, areNotificationsEnabled);
        BaseBussinessApp.getApp().setAppStatus(BaseBussinessApp.STATUS_NORMAL);

        if(!BuildConfig.DEBUG) {
            //如果为正式环境，不输出socketlog
            LogUtils.getConfig().setLogSwitch(false);
        }
        parseManifests();
    }

    @Override
    public void setStatusBarColor() {

    }

    private void init() {
        String ANDROID_ID = DeviceUtil.getIMEI();
        AccountHelper.id(BaseApp.getApp());
        if(m_rscDL == null) {
            m_rscDL = new ResourceDownload(this, ANDROID_ID);
            m_rscDL.getEventBus().register(this);
        }

        PushManager.getInstance().initialize(this.getApplicationContext(), MyGTPushService.class);
        // com.getui.demo.DemoIntentService 为第三  定义的推送服务事件接收类
        PushManager.getInstance().registerPushIntentService(this.getApplicationContext(), MyGTIntentService.class);
        int apnType = NetworkStateUtil.getAPNType(mContext);
        if (apnType == 0) {
            CheckDialog.initNetState(mContext);
        } else {
            if (NotificationManagerCompat.from(mContext).areNotificationsEnabled()) {
                getBundle();

            } else {
                if (SharedPreferenceUtil.getBoolean(mContext, Constant.NOTIFATION, false)) {
                    getBundle();
                } else {
                    CheckDialog.checkNotifation((SplashActivity) mContext, new SuccessCallBack() {
                        @Override
                        public void successcallback() {
                            getBundle();
                        }
                    });
                }
            }
        }
    }

    private void parseManifests() {
        String packageName = getApplicationContext().getPackageName();
        try {
            ApplicationInfo appInfo = getPackageManager().getApplicationInfo(packageName, PackageManager.GET_META_DATA);
            if (appInfo.metaData != null) {
                String appid = appInfo.metaData.getString("PUSH_APPID");
                String appsecret = appInfo.metaData.getString("PUSH_APPSECRET");
                String appkey = appInfo.metaData.getString("PUSH_APPKEY");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        PackageManager pkgManager = getPackageManager();

        // 读写 sd card 权限非常重要, android6.0默认禁止的, 建议初始化之前就弹窗让用户赋予该权限
        boolean sdCardWritePermission =
                pkgManager.checkPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        // read phone state用于获取 imei 设备信息
        boolean phoneSatePermission =
                pkgManager.checkPermission(Manifest.permission.READ_PHONE_STATE, getPackageName()) == PackageManager.PERMISSION_GRANTED;

        if (Build.VERSION.SDK_INT >= 23 && (!sdCardWritePermission || !phoneSatePermission)) {
            requestPermissions(new String[] {Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE},
                    REQUEST_PERMISSION);
        } else {
            init();
        }

        if (m_rscDL != null) {
            m_rscDL.onResume();
        }
    }

    private void getBundle() {
        if (m_rscDL.getState() == Thread.State.NEW) {
            m_rscDL.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (m_rscDL != null) {
            m_rscDL.onPause();
        }

    }


    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        view = getLayoutInflater().inflate(R.layout.activity_splash, null);
        mGuideContainer = view.findViewById(R.id.guide_container);
        mIndicator = view.findViewById(R.id.ci_indicator);
        mViewPager = view.findViewById(R.id.vp_guide);
        return view;
    }

    private void enterHomeActivity() {
        IApplicationProvider provider = RouterHelper.getProvider(RouterPath.APPLICATION_PROVIDER);
//        boolean is8Btc = AppCode.getMyAppCode(provider.getProjectBuildInfo().application_id).equals(AppCode.MAIN.code);
        boolean is8Btc = true;
        boolean isFirstInApp = SharedPreferenceUtil.getBoolean(mContext,Constant.IS_FIRST_IN_APP,true);
        String pushJson = getIntent().getStringExtra(Constant.PUSH_JSON);
        if (!TextUtils.isEmpty(pushJson)) {
            //如果推送的参数存在就传递给mainActivity,让它来处理跳转
//            ARouter.getInstance().build(RouterPath.MAIN_ACTIVITY)
//                    .withString(Constant.PUSH_JSON, pushJson)
//                    .navigation(this, mNavCallback);

            openHomePage();
//            ThrioNavigator.push("/home/home",
//                    new HashMap<>(),
//                    false,
//                    v -> {Log.d("ddd","");
//                    return null;}
//            );
            return;
        }
        if (isFirstInApp&&is8Btc) {
            showGuide();
        }else {
//            ARouter.getInstance().build(RouterPath.MAIN_ACTIVITY)
//                    .navigation(this, mNavCallback);
            openHomePage();
        }
    }

    private void openHomePage() {

        Log.d("flutterting", "openHomepage");
        ThrioNavigator.push("/home/home",
                "test",
                false,
                (v) -> {
                    return null;
                }
        );
        finish();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if(requestCode == REQUEST_PERMISSION){
            if (requestCode == REQUEST_PERMISSION) {
                if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
                    init();
                } else {
                    LogUtils.e("getuipush", "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
                            + "functions will not work");
                    init();
                }
            } else {
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            }
        }else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Permissions.changePermissionState(this, permissions[0], true);
            }
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onEvent(ResourceDownload.Event_DownloadStatus event) {
        if (event.m_status == ResourceDownload.WorkStatus.OK) {
            //是否同意了用户隐私协议，同意则直接进入app，否则弹出对话框
            boolean agreedUserAgreement = SharedPreferenceUtil.getBoolean(mContext,Constant.AGREED_USER_AGREEMENT,false);
            if (agreedUserAgreement){
                enterHomeActivity();
            }else {
                UserAgreementPopupWindow popupWindow = new UserAgreementPopupWindow(mContext, 0);
                popupWindow.setOnPositive(new UserAgreementPopupWindow.OnPositive() {
                    @Override
                    public void onPositive() {
                        //同意后，标识位置为true，以后不再询问
                        SharedPreferenceUtil.putBoolean(mContext,Constant.AGREED_USER_AGREEMENT,true);
                        enterHomeActivity();
                    }
                });
                popupWindow.showPopupWindow();
            }
        } else if(event.m_status == ResourceDownload.WorkStatus.FAIL) {
            ToastUtils.showLong(R.string.sys_query_timeout);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(m_rscDL != null) {
            m_rscDL.getEventBus().unregister(this);
        }
    }

    private void showGuide(){
        LayoutInflater inflater = LayoutInflater.from(mContext);
        View view1= inflater.inflate(R.layout.vp_guide_01,null);
        View view2= inflater.inflate(R.layout.vp_guide_02,null);
        View view3= inflater.inflate(R.layout.vp_guide_03,null);
        View view4= inflater.inflate(R.layout.vp_guide_04,null);
        View view5= inflater.inflate(R.layout.vp_guide_05,null);
        Button enter = view5.findViewById(R.id.btn_enter);
        enter.setOnClickListener(this);

        List<View> views = new ArrayList<>(8);
        views.add(view1);
        views.add(view2);
        views.add(view3);
        views.add(view4);
        views.add(view5);
        QuickPagerAdapter<View> pagerAdapter = new QuickPagerAdapter<>(mContext,views);
        mViewPager.setAdapter(pagerAdapter);
        mIndicator.setViewPager(mViewPager);
        mGuideContainer.setVisibility(View.VISIBLE);
    }

    @Override
    public void onClick(View v) {
        SharedPreferenceUtil.putBoolean(mContext,Constant.IS_FIRST_IN_APP,false);
//        ARouter.getInstance().build(RouterPath.MAIN_ACTIVITY)
//                .navigation(this, mNavCallback);
        openHomePage();

    }

    NavCallback mNavCallback = new NavCallback() {
        @Override
        public void onArrival(Postcard postcard) {
            finish();
        }
    };
}
